<?php
/***************************************************************************
 *   copyright : (C) 2009 Udrea Cristian
 *   site : http://code.google.com/p/testauction-php
 ***************************************************************************/

/***************************************************************************
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as 
 *   published by the Free Software Foundation; either version 2 of the
 *   License, or (at your option) any later version. Although none of the
 *   code may be sold. If you have been sold this script, get a refund.
 ***************************************************************************/
define('APP_ROOT', '../../');
//###############################################
include(APP_ROOT . 'include/session.php');
include('../library/functions.php');

// maximum width for all product image
define('MAX_PRODUCT_IMAGE_WIDTH', 300);
// the width for product box image
define('SMALL_WIDTH', 120);
// the width for product thumbnail
define('THUMBNAIL_WIDTH', 75);

if(!$session->logged_in && !$session->isAdmin()) {
	$session->logout();
	header('Location: index.php');
}

$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {

	case 'addProduct' :
		addProduct();
		break;

	case 'modifyProduct' :
		modifyProduct();
		break;

	case 'deleteProduct' :
		deleteProduct();
		break;

	case 'deleteImage' :
		deleteImage();
		break;

	case 'addAuction' :
		addAuction();
		break;

	default :
	    // if action is not defined or unknown
		// move to main product page
		header('Location: index.php');
}

function addProduct() {
    $name        = $_POST['txtName'];
	$description = $_POST['mtxDescription'];
	$price       = $_POST['txtPrice'];
	$detailLocal = $_POST['localSpec']; 
	$detailURL   = $_POST['txtSpecURL'];
	
	$images1 = uploadProductImage('fleImage1', '../../produse/');
	$images2 = uploadProductImage('fleImage2', '../../produse/');
	$images3 = uploadProductImage('fleImage3', '../../produse/');
	$images4 = uploadProductImage('fleImage4', '../../produse/');
	
	$sql   = "INSERT INTO " . TBL_PRODUCTS . " (product_name, shelf_price, description, detail_local, detail_url, 
			pict1_url, pict2_url, pict3_url, pict4_url) VALUES ('$name', '$price', '$description', '$detailLocal', 
			'$detailURL', '" . $images1['image'] . "', '" . $images2['image'] . "', '" . $images3['image'] 
			. "', '" . $images4['image'] . "')";

	execute_update($sql);

	header("Location: index.php");	
}

/*
	Upload an image and return the uploaded image name 
*/
function uploadProductImage($inputName, $uploadDir) {
	$image     = $_FILES[$inputName];
	$imagePath = '';
	$imgname = '';
	$thumbnailPath = '';
	
	// if a file is given
	if (trim($image['tmp_name']) != '') {
		$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

		// generate a random new file name to avoid name conflict
		$imgname = md5(rand() * time());
		$imagePath = $imgname . ".$ext";
		
		list($width, $height, $type, $attr) = getimagesize($image['tmp_name']); 

		// make sure the image width does not exceed the
		// maximum allowed width
		if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
			$result    = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
			$imagePath = $result;
		} else {
			$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
		}
		
		if ($result) {
			// create thumbnail
			$thumbnailPath =  "thumb_" . $imgname . ".$ext";
			$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);
			
			// create thumbnail failed, delete the image
			if (!$result) {
				unlink($uploadDir . $imagePath);
				$imagePath = $thumbnailPath = '';
			} else {
				$thumbnailPath = $result;
			}	
		} else {
			// the product cannot be upload / resized
			$imagePath = $thumbnailPath = '';
		}
		
		if ($result) {
			// create thumbnail
			$smallPath =  "small_" . $imgname . ".$ext";
			$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $smallPath, SMALL_WIDTH);
			
			// create thumbnail failed, delete the image
			if (!$result) {
				unlink($uploadDir . $imagePath);
				$imagePath = $smallPath = '';
			} else {
				$smallPath = $result;
			}	
		} else {
			// the product cannot be upload / resized
			$imagePath = $smallPath = '';
		}
	}

	return array('image' => $imagePath);//, 'thumbnail' => $thumbnailPath, 'small' => $smallPath);
}

/*
	Modify a product
*/
function modifyProduct() {
	/*$productId   = (int)$_GET['productId'];	
    $catId       = $_POST['cboCategory'];
    $name        = $_POST['txtName'];
	$description = $_POST['mtxDescription'];
	$price       = str_replace(',', '', $_POST['txtPrice']);
	$qty         = $_POST['txtQty'];
	
	$images = uploadProductImage('fleImage', SRV_ROOT . 'images/product/');

	$mainImage = $images['image'];
	$thumbnail = $images['thumbnail'];

	// if uploading a new image
	// remove old image
	if ($mainImage != '') {
		_deleteImage($productId);
		
		$mainImage = "'$mainImage'";
		$thumbnail = "'$thumbnail'";
	} else {
		// if we're not updating the image
		// make sure the old path remain the same
		// in the database
		$mainImage = 'pd_image';
		$thumbnail = 'pd_thumbnail';
	}
			
	$sql   = "UPDATE tbl_product 
	          SET cat_id = $catId, pd_name = '$name', pd_description = '$description', pd_price = $price, 
			      pd_qty = $qty, pd_image = $mainImage, pd_thumbnail = $thumbnail
			  WHERE pd_id = $productId";  

	$result = dbQuery($sql);
	
	header('Location: index.php');*/
}

/*
	Remove a product
*/
function deleteProduct() {
	if (isset($_GET['productId']) && (int)$_GET['productId'] > 0) {
		$productId = (int)$_GET['productId'];
	} else {
		header('Location: index.php');
	}
	// remove any references to this product
	$sql = "DELETE FROM " . TBL_AUCTIONS . " WHERE product_id = $productId";
	execute_update($sql);
	// get the image name and thumbnail
	$sql = "SELECT pict1_url, pict2_url, pict3_url, pict4_url FROM " . TBL_PRODUCTS . " WHERE product_id = $productId";
	$result = execute_query($sql);
	$row    = $result[0];
	// remove the product image and thumbnail
	for($i = 1; $i <= 4; $i++) {
		if ($row['pict' . $i . '_url']) {
			unlink('../../produse/' . $row['pict' . $i . '_url']);
			unlink('../../produse/' . 'thumb_' . $row['pict' . $i . '_url']);
			unlink('../../produse/' . 'small_' . $row['pict' . $i . '_url']);
		}
	}
	// remove the product from database;
	$sql = "DELETE FROM " . TBL_PRODUCTS . " WHERE product_id = $productId";
	execute_update($sql);
	header('Location: index.php');
}

/*
	Remove a product image
*/
function deleteImage() {
	if (isset($_GET['productId']) && (int)$_GET['productId'] > 0) {
		$productId = (int)$_GET['productId'];
	} else {
		header('Location: index.php');
	}
	$deleted = _deleteImage($productId, $_GET['imageIndex']);
	// update the image and thumbnail name in the database
	$sql = "UPDATE " . TBL_PRODUCTS . " SET pict" . $_GET['imageIndex'] . "_url = '' WHERE product_id = $productId";
	execute_query($sql);		
	header("Location: index.php?view=modify&productId=$productId");
}

function _deleteImage($productId, $index) {
	// we will return the status
	// whether the image deleted successfully
	$deleted = false;
	
	$sql = "SELECT pict" . $_GET['imageIndex'] . "_url FROM " . TBL_PRODUCTS . " WHERE product_id = $productId";
	$result = execute_query($sql) or die('Cannot delete product image. ' . mysql_error());
	
	if (count($result)) {
		$row = $result[0];
		
		if ($row['pict' . $_GET['imageIndex'] . '_url']) {
			// remove the image file
			$deleted = @unlink('../../produse/' . $row['pict' . $_GET['imageIndex'] . '_url']);
			$deleted = @unlink('../../produse/thumb_' . $row['pict' . $_GET['imageIndex'] . '_url']);
			$deleted = @unlink('../../produse/small_' . $row['pict' . $_GET['imageIndex'] . '_url']);
		}
	}
	
	return $deleted;
}

function addAuction() {
	$productId = $_POST['productId'];
	$interval = $_POST['txtInterval'];
	$price = (double)$_POST['txtPrice'];
	$offer = (double)$_POST['txtOffer'];
	$l24h = $_POST['lim24h'];
	$lfresh = $_POST['limFresh'];

	$dates = execute_query('SELECT starts_timestamp FROM '.TBL_AUCTIONS.' WHERE closed = 0 ORDER BY starts_timestamp DESC');
	if(count($dates) > 0) {
		$nextstart = getNextBestDate($dates[0]['starts_timestamp']);
	}
	else {
		$nextstart = getNextBestDate(time());
	}
	execute_update('INSERT INTO '.TBL_AUCTIONS.' (product_id, time_interval, one_time_24h, fresh_auction, base_price, offer_increment, 
		time_left, starts_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', array($productId, $interval, $l24h, $lfresh, $price, $offer,
		$interval, $nextstart));
	header('Location: index.php');
}
?>
